import { defineStore } from 'pinia'
import { ref } from 'vue'
import { movieApi } from '../utils/api'

export const useMovieStore = defineStore('movie', () => {
  const movies = ref([])
  const isLoading = ref(false)
  const error = ref(null)
  
  const fetchMovies = async () => {
    isLoading.value = true
    error.value = null
    try {
      const response = await movieApi.getList()
      movies.value = response.data
    } catch (err) {
      error.value = err.message || '获取商品列表失败'
    } finally {
      isLoading.value = false
    }
  }
  
  const addMovie = async (movieData) => {
    isLoading.value = true
    error.value = null
    try {
      await movieApi.create(movieData)
      await fetchMovies() // 刷新列表
    } catch (err) {
      error.value = err.message || '添加商品失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  return {
    movies,
    isLoading,
    error,
    fetchMovies,
    addMovie
  }
})